package com.zyw.boot.tool;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ExcelColumnConverter {

    public static void main(String[] args) {
        try {
            // 1. 读取Excel文件（支持.xlsx格式）
            FileInputStream file = new FileInputStream("C:\\Users\\yiwen_zheng\\Desktop\\装备字段翻译及限制.xlsx");
            Workbook workbook = new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0); // 处理第一个工作表

            // 2. 遍历所有行
            for (Row row : sheet) {
                Cell cell = row.getCell(0); // 获取第一列单元格
                if (cell == null) continue;

                // 3. 转换内容
                if (cell.getCellType() == CellType.STRING) {
                    String original = cell.getStringCellValue();
                    String converted = toSnakeCase(original);
                    cell.setCellValue(converted);
                }
            }

            // 4. 保存修改到新文件
            FileOutputStream outFile = new FileOutputStream("C:\\Users\\yiwen_zheng\\Desktop\\装备字段翻译及限制1.xlsx");
            workbook.write(outFile);
            outFile.close();
            System.out.println("转换完成！结果已保存到 output.xlsx");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static String toSnakeCase(String fieldName) {
        if (fieldName == null || fieldName.isEmpty()) {
            return fieldName;
        }

        StringBuilder snakeCase = new StringBuilder();
        char[] chars = fieldName.toCharArray();

        for (Integer i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (Character.isUpperCase(ch)) {
                // 如果当前字符是大写字母
                if (i != 0) {
                    // 检查前一个字符是否是小写字母，或者是否是一个连续的大写字母序列的结尾
                    if ('_'!=chars[i - 1] && (Character.isLowerCase(chars[i - 1]) ||
                            (i < chars.length - 1 && Character.isLowerCase(chars[i + 1])))) {
                        snakeCase.append('_');
                    }
                }
                snakeCase.append(Character.toLowerCase(ch));
            } else {
                snakeCase.append(ch);
            }
        }

        return snakeCase.toString();
    }
}